package com.harmony.pilot.llm.mcp;

import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Model Context Protocol (MCP) 客户端
 * 支持与MCP服务器通信，提供工具调用能力
 */
@Slf4j
@Component
public class MCPClient {
    
    private final ObjectMapper objectMapper;
    
    @Value("${mcp.server.url:http://localhost:3000}")
    private String mcpServerUrl;
    
    @Value("${mcp.enabled:false}")
    private boolean mcpEnabled;
    
    public MCPClient() {
        this.objectMapper = new ObjectMapper();
    }
    
    /**
     * 调用MCP工具
     */
    public Map<String, Object> callTool(String toolName, Map<String, Object> arguments) {
        if (!mcpEnabled) {
            log.warn("MCP is not enabled");
            return createErrorResponse("MCP is not enabled");
        }
        
        try {
            log.info("Calling MCP tool: {} with arguments: {}", toolName, arguments);
            
            // 构建请求
            Map<String, Object> request = new HashMap<>();
            request.put("method", "tools/call");
            request.put("params", Map.of(
                "name", toolName,
                "arguments", arguments
            ));
            
            // 发送HTTP请求
            String response = sendHttpRequest(mcpServerUrl + "/rpc", request);
            
            // 解析响应
            @SuppressWarnings("unchecked")
            Map<String, Object> result = objectMapper.readValue(response, Map.class);
            
            return result;
            
        } catch (Exception e) {
            log.error("Failed to call MCP tool: {}", toolName, e);
            return createErrorResponse("Failed to call MCP tool: " + e.getMessage());
        }
    }
    
    /**
     * 列出可用的MCP工具
     */
    public List<Map<String, Object>> listTools() {
        if (!mcpEnabled) {
            log.warn("MCP is not enabled");
            return List.of();
        }
        
        try {
            Map<String, Object> request = new HashMap<>();
            request.put("method", "tools/list");
            
            String response = sendHttpRequest(mcpServerUrl + "/rpc", request);
            
            @SuppressWarnings("unchecked")
            Map<String, Object> result = objectMapper.readValue(response, Map.class);
            
            @SuppressWarnings("unchecked")
            List<Map<String, Object>> tools = (List<Map<String, Object>>) result.get("tools");
            
            return tools != null ? tools : List.of();
            
        } catch (Exception e) {
            log.error("Failed to list MCP tools", e);
            return List.of();
        }
    }
    
    /**
     * 使用MCP增强代码上下文
     */
    public Map<String, Object> enhanceContext(String filePath, String code) {
        Map<String, Object> arguments = new HashMap<>();
        arguments.put("filePath", filePath);
        arguments.put("code", code);
        
        return callTool("enhance_context", arguments);
    }
    
    /**
     * 使用MCP分析代码依赖
     */
    public Map<String, Object> analyzeDependencies(String projectRoot, String filePath) {
        Map<String, Object> arguments = new HashMap<>();
        arguments.put("projectRoot", projectRoot);
        arguments.put("filePath", filePath);
        
        return callTool("analyze_dependencies", arguments);
    }
    
    /**
     * 使用MCP查询OpenHarmony API文档
     */
    public Map<String, Object> queryOHAPIDocs(String apiName) {
        Map<String, Object> arguments = new HashMap<>();
        arguments.put("apiName", apiName);
        
        return callTool("query_oh_api_docs", arguments);
    }
    
    /**
     * 发送HTTP请求
     */
    private String sendHttpRequest(String urlString, Map<String, Object> request) throws Exception {
        URL url = new URL(urlString);
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        
        conn.setRequestMethod("POST");
        conn.setRequestProperty("Content-Type", "application/json");
        conn.setDoOutput(true);
        
        // 发送请求体
        try (OutputStream os = conn.getOutputStream()) {
            byte[] input = objectMapper.writeValueAsBytes(request);
            os.write(input, 0, input.length);
        }
        
        // 读取响应
        StringBuilder response = new StringBuilder();
        try (BufferedReader br = new BufferedReader(
                new InputStreamReader(conn.getInputStream(), "utf-8"))) {
            String responseLine;
            while ((responseLine = br.readLine()) != null) {
                response.append(responseLine.trim());
            }
        }
        
        return response.toString();
    }
    
    /**
     * 创建错误响应
     */
    private Map<String, Object> createErrorResponse(String message) {
        Map<String, Object> error = new HashMap<>();
        error.put("error", true);
        error.put("message", message);
        return error;
    }
    
    /**
     * 检查MCP是否可用
     */
    public boolean isAvailable() {
        if (!mcpEnabled) {
            return false;
        }
        
        try {
            List<Map<String, Object>> tools = listTools();
            return !tools.isEmpty();
        } catch (Exception e) {
            log.warn("MCP server is not available", e);
            return false;
        }
    }
}

